<template>
    <basic-container>
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   :page.sync="page"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   v-model="form"
                   ref="crud"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @sort-change="sortChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   >
            <template #menu-left>
                <!--<el-button-->
                        <!--type="warning"-->
                        <!--icon="el-icon-download"-->
                        <!--@click="handleExport"-->
                <!--&gt;导出-->
                <!--</el-button>-->
              <el-button
                  type="warning"
                  icon="el-icon-download"
                  @click="handleExport"
              >导出
              </el-button>
              <el-button
                  type="warning"
                  icon="el-icon-download"
                  @click="handleExportStockCheck"
              >导出盘点单
              </el-button>
            </template>
        </avue-crud>
    </basic-container>
</template>

<script>
    import {purchaseSaleStock, getDetail, add, update, remove} from "@/api/anwise/stock/stock_summary";
    import {mapGetters} from "vuex";
    import { getToken } from '@/utils/auth';
    import { exportBlob,exportBlobPost } from '@/api/common';
    import { downloadXls } from '@/utils/util';
    import NProgress from 'nprogress';
    import 'nprogress/nprogress.css';
    import {stockHomeSelect,selectStockHomeDict} from "@/api/anwise/stock_home";

    export default {
        data() {
            return {
                form: {},
                query: {},
                loading: true,
                page: {
                    pageSize: 20,
                    currentPage: 1,
                    total: 0
                },
                selectionList: [],
                dateFormat: 'YYYY-MM-DD',
                pickerOptions: {},
                option: {
                    height:'auto',
                    calcHeight: 30,
                    tip: false,
                    searchShow: true,
                    searchMenuSpan: 6,
                    border: true,
                    index: true,
                    selection: false,
                    reserveSelection:true,
                    labelWidth: 150,
                    indexWidth:100,
                    menuWidth: 180,
                    addBtn: false,
                    editBtn: false,
                    viewBtn: false,
                    delBtn: false,
                    stripe: true,
                    searchIndex: 3,
                    searchIcon: false,
                    searchLabelWidth:120,
                    searchEnter:true,
                    menu:false,
                    column: [
                        {
                            label: "组织机构",
                            prop: "deptId",
                            type: "select",
                            filterable: true,
                            virtualize:true,
                            placeholder:'请输入组织机构',
                            dicUrl: '/api/blade-anwise/common/deptList?deptCategory=1',
                            props: {
                                label: 'deptName',
                                value: 'id',
                            },
                            dataType: 'string',
                            width:150,
                            rules: [{
                                required: true,
                                message: "请输入组织机构",
                                trigger: "blur"
                            }],
                            hide:true,
                        },
                        {
                            label: "组织机构",
                            prop: "deptName",
                            type: "input",
                            overHidden: true,
                            search: false,
                            width:160,
                        },
                        {
                            label: "报表仓位",
                            prop: "stockName",
                            type: "input",
                            overHidden: true,
                            search: false,
                            width:160,
                        },
                        {
                            label: "报表仓位",
                            prop: "stockId",
                            type: "select",
                            filterable: true,
                            hide:true,
                            dicData:[],
                            props: {
                                label: 'stockName',
                                value: 'id',
                            },
                            // allowCreate:true,
                            dataType: 'string',
                            search: true,
                            overHidden: true,
                            sortable: true,
                            width:120,
                        },
                        {
                            label: "日期区间",
                            prop: "dateRange",
                            type: "date",
                            format: 'YYYY-MM-DD',
                            valueFormat: 'YYYY-MM-DD',
                            searchRange: true,
                            search: true,
                            unlinkPanels:true,
                            hide:true,
                            width:120,
                        },
                        {
                            label: "物料编号",
                            prop: "materialNo",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            search:true,
                            width:180,
                            fixed:true,
                        },
                        {
                            label: "客户条码",
                            prop: "barCode",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            search:true,
                            width:180,
                            fixed:true,
                        },
                        {
                            label: "物料名称",
                            prop: "materialName",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            search:true,
                            width:180,
                        },
                        {
                            label: "规格",
                            prop: "specification",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            search:true,
                            width:180,
                        },
                        {
                            label: "单位",
                            prop: "unit",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "上期结余",
                            prop: "lastSurplus",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "本期入仓",
                            prop: "curInNum",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "本期出仓",
                            prop: "curOutNum",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "本期结余",
                            prop: "curSurplus",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "实际仓存汇总",
                            prop: "newTotalNum",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                        {
                            label: "差异数",
                            prop: "diffNum",
                            type: "input",
                            overHidden: true,
                            sortable: true,
                            width:180,
                        },
                      {
                        label: "差异标识",
                        prop: "diffInd",
                        type: "select",
                        filterable: true,
                        overHidden: true,
                        sortable: true,
                        width: 120,
                        dicUrl: "/blade-system/dict-biz/dictionary?code=biz_yes_no",
                        props: {
                          label: 'dictValue',
                          value: 'dictKey',
                        },
                        dataType: 'string',
                        search: true,
                      },
                        // {
                        //     label: "上期结+入-出-本期结",
                        //     prop: "result",
                        //     type: "input",
                        //     overHidden: true,
                        //     sortable: true,
                        //     width:200,
                        // },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["userInfo","permission"]),
            permissionList() {
                return {
                    checkPriceBtn: this.validData(this.permission.stock_in_check_price, false),
                    viewBtn: this.validData(this.permission.stock_in_details_view, false),
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
            this.loading = false;
            this.init();

        },
        methods: {
            init(){
                if (this.userInfo.role_name.includes('anwise_prod') || this.userInfo.role_name.includes('admin')) {
                    let deptName = this.findObject(this.option.column, 'deptId');
                    deptName.search = true;
                    // deptName.hide = false;
                }
                selectStockHomeDict().then(res=>{
                    if(res.data.success){
                        const stockId = this.findObject(this.option.column, 'stockId');
                        stockId.dicData = res.data.data;
                    }
                })
            },
            // handleExport(){
            //     NProgress.start();
            //     exportBlob(
            //         `/blade-anwise/stock/stock_summary/purchaseSaleStockExport?${this.website.tokenHeader
            //         }=${getToken()}`, this.query
            //     ).then(res => {
            //         downloadXls(res.data, `物料进销存统计${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
            //         NProgress.done();
            //     });
            // },
          handleExportStockCheck() {
            NProgress.start();
            exportBlobPost(
                `/blade-anwise/stock/stock_summary/exportStockCheck?${this.website.tokenHeader
                }=${getToken()}`, this.query
            ).then(res => {
              downloadXls(res.data, `盘点单${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
              NProgress.done();
            });
          },
            handleExport() {
              console.log("this.query",this.query);
            NProgress.start();
            exportBlobPost(
                `/blade-anwise/stock/stock_summary/purchaseSaleStockExport?${this.website.tokenHeader
                }=${getToken()}`, this.query
            ).then(res => {
              downloadXls(res.data, `进销存${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
              NProgress.done();
            });
          },
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            sortChange(val) {
                console.log(this.query)
                this.sort = {
                    prop: val.prop,
                    order: val.order
                };
                let order = "";
                if (this.sort.prop && this.sort.order) {
                    if (this.sort.order === "descending") {
                        order = `${this.sort.prop} desc`
                    } else {
                        order = `${this.sort.prop} asc`
                    }
                }
                this.query.orderBy = order;
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                // Object.assign(this.query, params)
                if(this.query.dateRange){
                    this.query.startTime = this.query.dateRange[0];
                    this.query.endTime = this.query.dateRange[1];
                }
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage){
                console.log(currentPage);
                this.page.currentPage = currentPage;
                this.onLoad(this.page);
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize;
                this.onLoad(this.page);
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            },
            onLoad(page, params = {}) {

                let filter = Object.assign(params, this.query);
                if (((this.userInfo.role_name.includes('anwise_prod') || this.userInfo.role_name.includes('admin')) && !filter.deptId  )) {
                    this.$message({
                        type: "error",
                        message: "请选择组织机构！!"
                    });
                    this.data = [];
                    return;
                }
                if (!filter.startTime || !filter.endTime) {
                    this.$message({
                        type: "error",
                        message: "请选择日期区间！!"
                    });
                    this.data = [];
                    return;
                }
                this.loading = true;
                if(filter.dateRange.length > 0){
                    params.startTime = filter.dateRange[0];
                    params.endTime = filter.dateRange[1];
                }
                filter.dateRange=[];
                purchaseSaleStock(page.currentPage, page.pageSize, filter).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                    this.loading = false;
                    this.selectionClear();
                });
            }
        }
    };
</script>

<style>
</style>
